#!/bin/bash
# 前端服务启动脚本 - 完整版（自动加载环境）

echo "=========================================="
echo "  🚀 启动前端服务 (完整版)"
echo "=========================================="
echo ""

# 尝试加载shell环境
if [ -f ~/.bashrc ]; then
    echo "📝 加载 ~/.bashrc ..."
    source ~/.bashrc
fi

if [ -f ~/.zshrc ]; then
    echo "📝 加载 ~/.zshrc ..."
    source ~/.zshrc
fi

# 尝试加载nvm
if [ -d ~/.nvm ]; then
    echo "📝 加载 nvm ..."
    export NVM_DIR="$HOME/.nvm"
    [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
fi

cd /data/Matrix/yy/gjj_pre_merge-v1/frontend

echo "📂 工作目录: $(pwd)"
echo "⏰ 启动时间: $(date '+%Y-%m-%d %H:%M:%S')"
echo ""

# 检查依赖
if [ ! -d "node_modules" ]; then
    echo "❌ 错误: node_modules不存在"
    echo "请先运行: npm install"
    exit 1
fi

echo "✅ 依赖检查通过"
echo ""

# 检查npm
echo "🔍 检查Node.js环境..."
if command -v npm &> /dev/null; then
    echo "   npm版本: $(npm --version)"
    echo "   node版本: $(node --version)"
    echo "   npm路径: $(which npm)"
elif command -v node &> /dev/null; then
    echo "   node版本: $(node --version)"
    echo "   node路径: $(which node)"
    echo "   ⚠️  npm未找到，将使用node直接运行"
else
    echo "❌ 错误: 找不到node和npm"
    echo ""
    echo "请检查Node.js是否已安装："
    echo "  1. 安装nvm: https://github.com/nvm-sh/nvm"
    echo "  2. 安装Node.js: nvm install --lts"
    echo "  3. 使用Node.js: nvm use --lts"
    exit 1
fi

echo ""
echo "🌐 启动开发服务器..."
echo "   端口: 5174"
echo "   地址: http://localhost:5174"
echo ""
echo "按 Ctrl+C 停止服务"
echo "=========================================="
echo ""

# 启动服务
if command -v npm &> /dev/null; then
    echo "✅ 使用npm启动..."
    npm run dev -- --port 5174 --host 0.0.0.0
elif command -v node &> /dev/null; then
    echo "✅ 使用node启动..."
    node ./node_modules/vite/bin/vite.js --port 5174 --host 0.0.0.0
else
    echo "❌ 无法启动服务"
    exit 1
fi

